import $service from '../../../service.js';
var log_id; //问诊id
var log_type; ////记录类型 1视频问诊 2图文问诊
var thenS_;
var isMeasured;
var page = 1

const app = getApp();
let oosParams = {};
let logId = '';
let imId = ''; // 对方imId
let inquiryPatientId = '';
let doctorId;
let chat = null;
let isImgShow = false

Page({
  txTic: null,
  webrtcroomComponent: null,
  /**
   * 页面的初始数据
   */
  data: {
    TRTCTYPE: $service.TRTCTYPE,
    tencentConfig: {}, // 音视频配置
    commentDetail: '', //评价内容
    advice: "", // 投诉建议
    scoreList: [{
      name: '综合评分',
      type: 'evaluate',
      evaluate: 1
    },{
      name: '服务质量评分',
      type: 'qualityEvaluate',
      evaluate: 1
    },{
      name: '服务态度评分',
      type: 'attitudeEvaluate',
      evaluate: 1
    },{
      name: '系统使用评分',
      type: 'systemEvaluate',
      evaluate: 1
    }],
    msgList: [],
    doctorEnd: false, //医生是否结束问诊
    userIDImg: '',
    selToID: "", //对方聊天账号
    selToIDImg: '',
    scrollTop: 0,
    increase: false, //图片添加区域隐藏
    aniStyle: true, //动画效果
    message: "",
    imUserInfo: {}, //im用户信息
    imSelToUserInfo: {}, //im对方用户信息
    isJoinClassroom: false, // 是否已经在课堂中
    template: '1v1bigsmall', //视频用
    smallViewLeft: 'calc(100vw - 20vw - 1vw)', //视频用
    smallViewTop: 'calc(1vw)', //视频用
    smallViewWidth: '20vw', //视频用
    smallViewHeight: '26vw',
    enableCamera: true, // 是否启用摄像头
    loadingImg: '',
    playerBackgroundImg: '',
    boardShowFullScreen: true, // 是否全屏显示白板
    boardHidden: true,
    doctor_img: '../../../static/images/head.png', //医生头像
    doctor_name: '', //医生名称
    logList: [], //排队人员
    isshow: false,
    rtsytViewZt: true, //人体示意图显示隐藏
    log_type: 2,
    inputHeight: 0, //监听input弹起高度
    openPageBox: 0, //1录入测量数据 2上传图片 3 图片列表 4处方验单 5测量数据 6处方详情 7检验检查 8健康指导 9住院建议 10评价弹窗 11候诊列表
    jswz_active: 1, //评价
    openPageBox_up: 0,
    measuredDataMap_user: {
      dataAnimalHeat: '', //体温
      dataSbp: '', //收缩压
      dataDbp: '', //舒张压
      dataHeartRate: '', //心率
      dataRr: '', //呼吸频率
      dataGlu: '', //血糖
      dataCondition: '', //	测量条件
      dataParameter: '3.61～6.11mmol／L(65～110mg／dl)', //测量参数
    },
    txclsj_list: [],
    txclsj_isshow: false,
    measuredDataList: [], //测量数据list
    measuredDataMap: {}, //测量数据map
    num: 0, //测量数据
    loadingText: '',
    loadingType: true,
    timeList: [], //图片列表
    imgAttay: [], //指定上传图片的集合
    dataMap: {}, //处方验单
    prescription_imgurl: '', //处方详情 图片
    checklist_imgurl: '', //检验检查详情 图片
    guidance_imgurl: '', //健康指导详情 图片
    guidanceData: {}, // 健康详情数据
    hospitalization_imgurl: '', //住院建议详情 图片
    application_imgurl: '', // 申请单 图片
    isinfolook: false,
    winH: '', //窗口高度
    showModal: false, // 弹窗显示
    modalContent: '', // 弹窗内容
    showWait: true, //是否显示等待按钮
    log_type: '', // 问诊类型
    isWithdrawShow: false, // 是否展示撤回弹窗
    toView: '',
    messageHeight: '', // 底部操作栏高度
    refundDialogShow: false,
    myIM: '', // 自己的IMid
    friendIM: '', // 对方的IMid
    logId: '',
    doctorId: '',
    isCompleted: '',
    chatType: '',
    doctorName: "",
  },
  onLoad(e) {
    imId = e.imId;
    logId = e.logId;
    doctorId = e.doctorId;
    inquiryPatientId = e.inquiryPatientId;
    log_id = e.logId
    log_type = e.log_type
    //e.chatType判断问诊是否结束1为结束
    console.log(e.chatType);
    this.setData({
      chatType: e.chatType,
      log_type,
      friendIM: e.imId,
      myIM: e.myIM,
      logId: e.logId,
      doctorId: e.doctorId,
      doctorName: e.doctorName,
      isCompleted: e.isCompleted
    })
    thenS_ = this.data;
    wx.setNavigationBarTitle({
      title: `${e.doctorName}医生`
    })
    // this.publicUtil_getInquiryLogDetails();
    wx.hideHomeButton()
    this.getMessageheight();
    if (log_type == 1 && !this.data.doctorEnd) {
      this.webrtcroomComponent = this.selectComponent('#webrtcroom');
      this.startRTC();
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onShow() {
    wx.showLoading()
    wx.hideLoading()
    this.publicUtil_getInquiryLogDetails();
    wx.setKeepScreenOn({
      keepScreenOn: true
    })
    thenS_ = this.data;
    this.initWebSocket();
    this.ossPolicy(); // 获取oss参数
    this.watchNetWork(); // 监听网络变化
    chat = this.selectComponent('#chat')
    if (!isImgShow) {
      this.isRead() //调用一次39确保已读
    }
    isImgShow = false
    if (this.data.log_type == 1) {
      // wx.RecorderManager().start()
      // wx.LivePusherContext().start()
    }
  },
  onReady() {
    this.bottom();
  },
  // 页面卸载
  onUnload() {
    // this.txTic.quitClassroom((res) => {});
    // 停止音视频
    this.upDataChat()
    if (log_type == 1) {
      this.webrtcroomComponent.exitRoom();
    }
  },
  // 更新未读聊天信息
  upDataChat() {
    app.webSocket.sendWebSocketMsg({
      data: {
        "userId": this.data.myIM,
        "packageType": 40,
      },
    })
  },
  //  初始化webSocket
  initWebSocket() {
    if (!app.webSocket.init) {
      app.webSocket.initWebSocket({
        url: $service.wsUrl
      });
    }
    app.webSocket.isInvited = false;
    this.sendLogin();
    app.webSocket.onReceivedMsg(res => { // 接收webSocket信息
      console.log(res);
      if (res.packageType === 4) { // 接收对方聊天消息
        console.log(res)
        if (res.msgType == 7) { // 当对方重新进入聊天室时刷新页面
          this.publicUtil_getInquiryLogDetails();
          chat.getChatRecordList('reset')
        } else if (res.msgType == 8) {
          chat.isReadMessage()
        } else if (res.msgType == 5) {
          chat.tagetMessage(res);
        } else if (res.msgType == 6) {
          chat.tagetMessage(res);
        } else {
          if (res.userId == this.data.friendIM || (res.msgUserName == this.data.doctorName && res.userId == 0)) {
            this.isRead()
            chat.tagetMessage(res);
          }
        }
      } else if (res.packageType === 3) { // 接收自己发出的聊天消息
        if (res.msgType != 6) {
          chat.tagetMessage(res);
        }
      } else if (res.packageType === 17 || res.packageType === 18) { // 接收医生修改问诊消息消息
        this.publicUtil_getInquiryLogDetails();
      }
      // 如果是图文和视频问诊才接收医生在线状态的信息
      if (log_type == 1 || log_type == 2) {
        if (res.packageType === 23) { // 接收医生1分钟后没有重新连信息
          this.setData({
            modalContent: '医生网络不佳暂时掉线，建议您等待医生重新连接。若结束问诊，诊查费在1-3个工作日原路返回。您也可以返回首页，选择其他医生。',
            showModal: true,
            showWait: true,
          })
        } else if (res.packageType === 25) {
          this.setData({
            modalContent: '医生已离开。若结束问诊，诊查费在1-3个工作日原路返回。您也可以返回首页，等待医生上线或选择其他医生。',
            showWait: false,
            showModal: true
          })
        } else if (res.packageType === 27) {
          this.setData({
            modalContent: '医生未能重连成功，请返回首页选择其他医生。',
            showWait: false,
            showModal: true
          })
        } else if (res.packageType === 28) {
          chat.getChatRecordList('reset')
          this.setData({
            showModal: false,
            refundDialogShow: false
          })
        } else if (res.packageType === 16) { // 接收患者被分诊消息
          if (log_type == 1) {
            this.webrtcroomComponent.exitRoom();
          }
          wx.showModal({
            title: '提示',
            content: '医生已分诊，当前问诊费会在1-3个工作日原路返回',
            confirmText: "确定",
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.reLaunch({
                  url: '../../user_index/user_index'
                })
              }
            }
          })
        } else if (res.packageType === 14) { // 接收结束问诊消息
          if (imId == res.imId) {
            if (log_type == 1) {
              this.webrtcroomComponent.exitRoom();
            }
            $service.showToast('医生已结束问诊');
            this.publicUtil_getInquiryLogDetails();
            this.data.doctorEnd = true
            setTimeout(() => {
              wx.reLaunch({
                url: `./evaluate/evaluate?logId=${logId}&inquiryPatientId=${inquiryPatientId}`,
              })
            }, 1000)
          }
        }
      }
      //家庭医生和复诊需要判断医生结束问诊
      else {
        if (res.packageType === 14) { // 接收结束问诊消息
          this.setData({
            doctorEnd: true
          })
        }
      }
    })
  },
  // 向对方发送上线信息
  sendLogin() {
    app.webSocket.sendWebSocketMsg({ // 告诉对方已上线
      data: {
        "userIm": this.data.myIM, //发送方im
        "friendIm": this.data.friendIM,
        "packageType": 38,
      },
    })
  },
  //问诊详情
  publicUtil_getInquiryLogDetails() {
    app.http.getAllInfo({
      id: logId
    }).then(res => {
      var inquiryMap = $service.deepClone(res.data);
      let arr = [];
      if (inquiryMap.diagnosisArray) {
        inquiryMap.diagnosisArray.forEach(item => {
          arr.push(item.diagnosis)
        })
        inquiryMap.diagnosis = arr.join();
      }
      // console.log(inquiryMap);
      this.setData({
        dataMap: inquiryMap,
        selToIDImg: inquiryMap.doctorHeadImg,
        userIDImg: JSON.parse($service.getStore('userData')).userImg
      })
    }).catch(err => {
      $service.showToast(err.msg);
    })
  },
  publicUtilgetInquiryLogDetails() {
    let params = {
      "current": 1,
      "logId": logId,
      "size": 10
    }
    app.http.getMeasureDataList(params).then(res => {
      if (res.data.list.length != 0) {
        let data = $service.deepClone(res.data.list[0])
        // if ($service.isUndefinedAndEmpty(data.dataCondition)) { //	测量条件
        //   data.dataCondition = '请选择'
        // }
        console.log(data)
        isMeasured = 1; //判断本次问诊有没有填写测量数据
        this.setData({
          measuredDataMap_user: data
        })
      }
    }).catch(err => {
      $service.showToast(err.msg);
    })
  },
  //事件处理函数
  send: function () {
    var that = this;
    if (this.data.message == "") {
      wx.showToast({
        title: '消息不能为空哦~',
        icon: "none",
        duration: 2000
      })
    } else {
      if (this.data.doctorEnd) {
        $service.showToast('问诊已结束')
      } else {
        that.bottom()
        let msgData = {
          "msgText": this.data.message, // 信息体
          "msgUserName": this.data.dataMap.patientName,
          "friendId": imId, // 接收方的用户imID
          "msgType": 0, // 消息类型；0文字消息、1固定表情 3 图片url  4撤回消息 5系统消息
          "inquiryLogId": logId,
          "msgDate": $service.getDate(), // 发送时间
          "packageType": 3, // 信息包类型
        }
        app.webSocket.sendWebSocketMsg({
          data: msgData,
          success: () => {
            this.setData({
              message: "",
              increase: false
            })
          },
          fail: () => {
            $service.showToast('发送失败')
          }
        })
      }
    }
  },
  //监听input值的改变
  bindChange(res) {
    this.setData({
      message: res.detail.value
    })
  },
  cleanInput() {
    //button会自动清空，所以不能再次清空而是应该给他设置目前的input值
    this.setData({
      message: this.data.message
    })
  },
  increase() {
    this.data.increase = !this.data.increase
    this.setData({
      increase: this.data.increase,
      aniStyle: true,
      isWithdrawShow: false
    })
  },
  //点击空白隐藏message下选框
  outbtn() {
    this.setData({
      aniStyle: true,
      isWithdrawShow: false
    })
  },
  //聊天消息始终显示最底端
  bottom: function () {
    this.setData({
      toView: 'flag'
    })
  },
  //返回顶部
  getpageScrollTo() {
    wx.pageScrollTo({
      scrollTop: 0
    })
  },
  //收到对方的消息，确认已读
  isRead() {
    // 传递一个39事件保证已读
    let dataMsg = {
      "userId": this.data.friendIM, //发送方id
      "friendId": this.data.myIM, //接收方id
      "packageType": 39,
    }
    app.webSocket.sendWebSocketMsg({
      data: dataMsg,
      success: (res) => {
        console.log(res);
      }
    })
  },
  // 开始RTC
  startRTC() {
    if (!$service.getStore('tencentConfigP')) return
    let tencentConfig = JSON.parse($service.getStore('tencentConfigP'))
    console.log('tencentConfig',tencentConfig)
    this.setData({
      tencentConfig,
      boardShowFullScreen: false
    });
  },
  openPage(e) { // 1测量数据 2 上传图片 3家庭医生和复诊退款 4已开处方/指导 5取消排队 6结束问诊弹窗 7确认结束问诊
    var index = e.currentTarget.dataset.index
    this.publicUtil_getInquiryLogDetails()
    thenS_.openPageBox_up = thenS_.openPageBox
    if (index == 1) {
      if (this.data.doctorEnd) {
        wx.showToast({
          title: '医生已结束问诊~',
          icon: "none",
          duration: 2000
        })
      return
      } else {
        this.getMeasuringConditionList();
        this.publicUtilgetInquiryLogDetails()
      }
    } else if (index == 3) {
      wx.showModal({
        content: `医生尚未接诊，确认退款？`,
        cancelText: '退款',
        confirmText: '取消',
        confirmColor: '#1189FF',
        success: (res) => {
          if (res.cancel) {
            wx.showLoading({
              title: "退款请求中",
              mask: true
            });
            let params = {
              "doctorId": this.data.dataMap.doctorId,
              "userId": JSON.parse($service.getStore('userInfo')).id,
              "isFrozen": 0
            }
            app.http.refund(params).then(res => {
              $service.showToast('退费成功');
              this.endInquiry()
              setTimeout(() => {
                wx.reLaunch({
                  url: '/pages/user_index/user_index'
                })
              }, 2000)
            }).catch(err => {
              $service.showToast(err.msg);
            }).finally(res => {
              wx.hideLoading();
            })
          }
        },
      })
    } else if (index == 4) {
      this.setData({
        isinfolook: false,
        openPageBox: 4
      })
    } else if (index == 5) {
      console.log('取消排队=====' + log_id)
      var jsonData = {
        "log_id": log_id
      }
      var jsonAjax = {
        "url": "userSide_personal_inquiry_updateCancelQueue.do",
        "jsonData": jsonData,
      }
      $service.getAjaxData(jsonAjax, function (jsonBack) {
        $service.showToast('取消成功')
        setTimeout(function () {
          wx.reLaunch({
            url: '/pages/user_index/user_index'
          })
        }, 1000);
      })
    } else if (index == 6) {
      wx.showModal({
        title: '提示',
        content: '您确定结束问诊吗？',
        success: (res) => {
          if (res.confirm) {
            app.webSocket.sendWebSocketMsg({
              data: {
                "logId": logId,
                "packageType": 13
              },
              success: (res) => {
                wx.reLaunch({
                  url: `./evaluate/evaluate?logId=${logId}&inquiryPatientId=${inquiryPatientId}`,
                })
              },
              fail: (err) => {
                $service.showToast('结束失败');
              }
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return
    } else if (index == 7) { //结束问诊
      var this_ = this;
      if (!this.data.commentDetail) {
        $service.showToast('请输入评价内容')
        return
      }
      let params = {
        "userType": thenS_.dataMap.userType,
        "doctorId": Number(doctorId),
        "inquiryPatientId": Number(inquiryPatientId),
        "advice": this.data.advice,
        "logId": logId,
        "commentDetail": this.data.commentDetail
      }
      this.data.scoreList.forEach(item => {
        params[item.type] = item.evaluate
      })
      app.webSocket.sendWebSocketMsg({
        data: {
          "logId": logId,
          "packageType": 13
        },
        success: (res) => {
          app.http.comment(params).then(res => {
            $service.showToast('结束问诊成功')
            setTimeout(function () {
              wx.reLaunch({
                url: '/pages/user_side/personal/personal_prescription/personal_prescription'
              })
            }, 500);
          }).catch(err => {
            $service.showToast(err.msg)
          })
        },
        fail: (err) => {
          $service.showToast('结束失败');
          setTimeout(function () {
            wx.reLaunch({
              url: '/pages/user_side/personal/personal_prescription/personal_prescription'
            })
          }, 500);
        }
      })
    }

    if (index == 1 || index == 2 || index == 4) {
      thenS_.openPageBox = index;
    }
    this.setData({
      increase: false,
      openPageBox: thenS_.openPageBox,
      openPageBox_up: thenS_.openPageBox_up,
      isWithdrawShow: false
    })
    if (index == 1 || index == 2 || index == 4) {
      this.getpageScrollTo()
    }
  },
  // 填写评价内容
  inputEvaluate(e) {
    let {index} = e.currentTarget.dataset
    let {value} = e.detail
    if  (index == 1) {
      this.data.commentDetail  = value
    } else if (index == 2) {
      this.data.advice  = value
    }
    this.setData({
      commentDetail: this.data.commentDetail,
      advice: this.data.advice
    })
  },
  // 结束问诊
  endInquiry() {
    app.http.unSuccessfulInquiry({
      id: logId
    }).then(res => {
      $service.showToast('退费成功');
    }).catch(err => {
      $service.showToast(err.msg);
    })
  },
  tapjswz_active(e) {
    var index = e.currentTarget.dataset.index;
    var num = e.currentTarget.dataset.num;
    this.data.scoreList[num].evaluate = Number(index)
    this.setData({
      scoreList: this.data.scoreList
    })
  },
  //关闭弹窗
  closeBox(e, num) { //1录入测量数据 2上传图片 3 图片列表 4处方验单 5测量数据 6处方详情 7检验检查 8健康指导 9住院建议 10结束问诊
    // console.log(e)

    if (num == 1) {
      var index = 2; //1关闭全部弹窗   2关闭当前弹窗
    } else {
      var index = e.currentTarget.dataset.index; //1关闭全部弹窗   2关闭当前弹窗
      var num = e.currentTarget.dataset.num; //

      if (num == 1) {
        this.publicUtil_getInquiryLogDetails()
      }
    }
    var This_openPageBox = 0
    if (index == 1) {
      This_openPageBox = 0
    } else {
      if (thenS_.openPageBox == 1 || thenS_.openPageBox == 2 || thenS_.openPageBox == 4 || thenS_.openPageBox == 10) {
        This_openPageBox = 0
      } else {
        This_openPageBox = thenS_.openPageBox_up
      }
    }
    this.setData({
      openPageBox: This_openPageBox
    })
    if (This_openPageBox == 0) {
      this.bottom()
    }
  },

  setToolType(e) {
    // console.log(e)
    var index = e.currentTarget.dataset.index
    if (index == "3") {
      this.data.teduBoard.clear(false);
    } else {
      this.data.teduBoard.setToolType(index)
    }
  },
  inputFocus(e) {
    this.setData({
      isWithdrawShow: false,
      increase: false,
    })
    var inputHeight = 0
    if (e.detail.height) {
      inputHeight = e.detail.height * 750 / wx.getSystemInfoSync().windowWidth
      this.setData({
        inputHeight,
        messageHeight: inputHeight + this.data.messageHeight
      })
    }
    this.bottom();
  },
  inputBlur() {
    console.log('键盘收起')
    this.getMessageheight()
    this.setData({
      inputHeight: 0,
      increase: false,
    })
  },




  // --------------填写测量数据
  //获取测量条件
  getMeasuringConditionList() {
    app.http.getMeasuringConditionList().then(res => {
      this.setData({
        txclsj_list: res.data.list
      })
    })
  },
  //选择测量条件
  tapisshow(e) {
    // console.log(e)
    var index = e.currentTarget.dataset.index;
    if (index == 1) {
      this.data.txclsj_isshow = !this.data.txclsj_isshow
    } else if (index == 2) {
      var num = e.currentTarget.dataset.num;
      this.data.measuredDataMap_user.dataCondition = this.data.txclsj_list[num].conditionName;
      this.data.txclsj_isshow = false;
    }
    this.setData({
      txclsj_isshow: this.data.txclsj_isshow,
      measuredDataMap_user: this.data.measuredDataMap_user
    })
  },

  inputChange(e) {
    var index = e.currentTarget.dataset.index;
    if (index == 1) { //体温
      this.data.measuredDataMap_user.dataAnimalHeat = e.detail.value
    } else if (index == 2) { //心率
      this.data.measuredDataMap_user.dataHeartRate = e.detail.value
    } else if (index == 3) { //收缩压
      this.data.measuredDataMap_user.dataSbp = e.detail.value
    } else if (index == 4) { //舒张压
      this.data.measuredDataMap_user.dataDbp = e.detail.value
    } else if (index == 5) { //呼吸频率
      this.data.measuredDataMap_user.dataRr = e.detail.value
    } else if (index == 6) { //血糖
      this.data.measuredDataMap_user.dataGlu = isNaN(e.detail.value) ? e.detail.value : Number(e.detail.value).toFixed(2)
    } else if (index == 7) { //测量参数
      this.data.measuredDataMap_user.dataParameter = e.detail.value
    }
    this.setData({
      measuredDataMap_user: this.data.measuredDataMap_user
    })
  },
  submission(e) {
    var this_ = this
    var index = e.currentTarget.dataset.index;
    if (index == 1) { //录入数据
      if (!$service.isUndefinedAndEmpty(this.data.measuredDataMap_user.dataSbp)) {
        if (this.data.measuredDataMap_user.dataDbp == '') {
          $service.showToast('有填写收缩压就必须填写舒张压');
          return;
        }
      }
      if (!$service.isUndefinedAndEmpty(this.data.measuredDataMap_user.dataDbp)) {
        if (this.data.measuredDataMap_user.dataSbp == '') {
          $service.showToast('有填写舒张压就必须填写收缩压');
          return;
        }
      }
      if (Number(this.data.measuredDataMap_user.dataSbp) < Number(this.data.measuredDataMap_user.dataDbp)) {
        $service.showToast('收缩压必须大于舒张压');
        return;
      }
      if (isNaN(this.data.measuredDataMap_user.dataGlu)) {
        $service.showToast('请录入正确的血糖值');
        return;
      }
      if (!$service.isUndefinedAndEmpty(this.data.measuredDataMap_user.dataGlu)) {
        if (!this.data.measuredDataMap_user.dataCondition) {
          $service.showToast('录入血糖必须选择测量条件');
          return;
        }
      }
      if ($service.isUndefinedAndEmpty(this.data.measuredDataMap_user.dataAnimalHeat) && $service.isUndefinedAndEmpty(this.data.measuredDataMap_user.dataSbp) && $service.isUndefinedAndEmpty(this.data.measuredDataMap_user.dataDbp) && $service.isUndefinedAndEmpty(this.data.measuredDataMap_user.dataHeartRate) && $service.isUndefinedAndEmpty(this.data.measuredDataMap_user.dataRr) && $service.isUndefinedAndEmpty(this.data.measuredDataMap_user.dataGlu)) {
        $service.showToast('至少要输入一项测量内容');
        return;
      }
      // if (this.data.measuredDataMap_user.dataCondition == '请选择') { //	测量条件
      //   var dataCondition = ''
      // } else {
      //   var dataCondition = this.data.measuredDataMap_user.dataCondition
      // }
      let params = {
        "logId": logId,
        "dataAnimalHeat": this.data.measuredDataMap_user.dataAnimalHeat, //体温
        "dataSbp": this.data.measuredDataMap_user.dataSbp, //收缩压
        "dataDbp": this.data.measuredDataMap_user.dataDbp, //舒张压
        "dataHeartRate": this.data.measuredDataMap_user.dataHeartRate, //心率
        "dataRr": this.data.measuredDataMap_user.dataRr, //呼吸频率
        "dataGlu": this.data.measuredDataMap_user.dataGlu, //血糖
        "dataCondition": this.data.measuredDataMap_user.dataCondition, //	测量条件
        "dataParameter": this.data.measuredDataMap_user.dataParameter, //测量参数
      }
      if (isMeasured == 1) {
        app.http.updateMeasureData(params).then(res => {
          $service.showToast(res.msg)
          this.setData({
            openPageBox: 0
          })
          this.bottom()
        }).catch(err => {
          $service.showToast(err.msg)
        })
      } else {
        app.http.addMeasureData(params).then(res => {
          $service.showToast(res.msg)
          this.setData({
            openPageBox: 0
          })
          this.bottom()
        }).catch(err => {
          $service.showToast(err.msg)
        })
      }
    } else if (index == 2) {
      page = 1
      this.publicUtil_getPatientMeasuredDataList('history')
      this.publicUtil_getPatientMeasuredDataList('now')
      thenS_.openPageBox_up = thenS_.openPageBox
      this_.setData({
        openPageBox: 5,
        openPageBox_up: thenS_.openPageBox_up
      })
      this_.getpageScrollTo()
    } else if (index == 3) {
      var urls = 'http://zz.nxk520.com/fjzl/egzz/zz_view_jcdata.html?idno=' + thenS_.dataMap.inquiryMap.inquiry_patient_idcard
      $service.openPage('../../user_side/index/index_outerchain/index_outerchain?url=' + urls)
    }
  },
  onPullDownRefresh() {
    page = 1;
    this.setData({
      loadingText: '加载更多'
    })
    this.publicUtil_getPatientMeasuredDataList('history');
    this.publicUtil_getPatientMeasuredDataList('now');
    wx.stopPullDownRefresh()
  },
  onReachBottom: function () {
    if (thenS_.loadingType == true) {
      page++
      this.publicUtil_getPatientMeasuredDataList('history');
    } else {
      this.setData({
        loadingText: '没有更多了'
      })
    }
  },
  loading() {
    if (thenS_.loadingType == true) {
      page++
      this.publicUtil_getPatientMeasuredDataList('history')
    } else {
      this.setData({
        loadingText: '没有更多了'
      })
    }
  },
  //获取历史测量数据
  publicUtil_getPatientMeasuredDataList: function (type) {
    let params = {
      "current": page,
      "size": 10
    }
    if (type == 'now') {
      params.logId = Number(logId)
    } else {
      params.identityCard = this.data.dataMap.patientIdcard
    }
    app.http.getMeasureDataList(params).then(res => {
      let measuredDataList = [];
      if (type == 'now') {
        thenS_.measuredDataMap = res.data.list[0]
      } else {
        measuredDataList = res.data.list
        if (page == 1) {
          thenS_.loadingText = '';
          thenS_.measuredDataList = measuredDataList;
        } else {
          if (measuredDataList.length <= 0) {
            thenS_.loadingType = false;
            thenS_.loadingText = '没有更多了';
          } else {
            for (var i = 0; i < measuredDataList.length; i++) {
              thenS_.measuredDataList.push(measuredDataList[i]);
              thenS_.loadingText = '加载更多';
            }
          }
        }
      }
      this.setData({
        measuredDataMap: thenS_.measuredDataMap,
        measuredDataList: thenS_.measuredDataList,
        loadingText: thenS_.loadingText,
        loadingType: thenS_.loadingType
      })
    }).catch(err => {
      $service.showToast(err.msg)
    })
  },
  previewImage: function (e) { //图片放大
    var index = e.currentTarget.dataset.index;
    var num = e.currentTarget.dataset.num;
    var all = [];
    if (num == 1) {
      all.push(this.data.timeList[index].img_src);
    } else if (num == 2) {
      all.push(this.data.prescription_imgurl);
    } else if (num == 3) {
      all.push(this.data.checklist_imgurl);
    } else if (num == 4) {
      all.push(this.data.guidance_imgurl);
    } else if (num == 5) {
      all.push(this.data.hospitalization_imgurl);
    } else if (num == 6) {
      all.push(this.data.application_imgurl);
    }
    all.forEach(item => {
      item = item.replace(/https/, 'http')
    })
    wx.previewImage({
      urls: all
    })
  },
  // oss信息
  ossPolicy() {
    app.http.ossPolicy().then(res => {
      oosParams = res.data;
    })
  },
  // 上传图片 newok
  uploadImg: function () {
    if (this.data.doctorEnd) {
      wx.showToast({
        title: '医生已结束问诊~',
        icon: "none",
        duration: 2000
      })
    } else {
      var this_ = this;
      this.setData({
        isWithdrawShow: false
      })
      isImgShow = true
      wx.chooseImage({
        count: 1,
        success: function (res) {
          const tempFilePaths = res.tempFilePaths;
          wx.uploadFile({
            url: oosParams.host,
            filePath: tempFilePaths[0],
            name: 'file',
            formData: {
              name: $service.randomFilename(tempFilePaths[0]),
              key: oosParams.dir + $service.randomFilename(tempFilePaths[0]),
              dir: oosParams.dir,
              policy: oosParams.policy,
              OSSAccessKeyId: oosParams.accessid,
              success_action_status: "200", //让服务端返回200,不然，默认会返回204
              callback: oosParams.callback,
              signature: oosParams.signature
            },
            success: (uploadFileRes) => {
              let imgData = JSON.parse(uploadFileRes.data)
              if (imgData.code === 1) {
                let data = {
                  "msgText": imgData.data.filename, // 信息体
                  "friendId": imId, // 接收方的用户imID
                  "msgType": 3, // 消息类型；0文字消息、1固定表情 3 图片url
                  "inquiryLogId": logId,
                  "msgUserName": this_.data.dataMap.patientName,
                  "msgDate": $service.getDate(), // 发送时间
                  "packageType": 3, // 信息包类型
                }
                app.webSocket.sendWebSocketMsg({
                  data,
                  success: (res) => {
                    this_.setData({
                      increase: false
                    })
                  },
                  fail: (err) => {
                    $service.showToast(err.errMsg);
                  }
                })
              }
            },
            fail: (res => {
              $service.showToast('上传oss失败')
            })
          });
        },
      });
    }
  },
  gotodetalis(e) {
    var index = e.currentTarget.dataset.index;
    var num = e.currentTarget.dataset.num;
    thenS_.openPageBox_up = thenS_.openPageBox;
    if (index == 1) { //检验检查
      thenS_.openPageBox = 7
      //  this.publicUtil_getInquiryLogChecklistDetails(this.data.dataMap.checklistList[num].checklist_id)
      this.getEstablishPdf(this.data.dataMap.inspectionOpinionList[num].id, 3)
    } else if (index == 2) { //健康指导
      thenS_.openPageBox = 8
      this.getEstablishPdf(this.data.dataMap.inquiryLogHealthGuidanceList[num].id, 2)
    } else if (index == 3) { //住院建议
      thenS_.openPageBox = 9
      this.getEstablishPdf(this.data.logId, 1)
    } else if (index == 4) { //处方
      thenS_.openPageBox = 6;
      this.getEstablishPdf(this.data.dataMap.prescriptionList[num].id, 4)
    } else if (index == 5) { //申请单
      thenS_.openPageBox = 12;
      this.getEstablishPdf(this.data.dataMap.formListResult[num].id, 5, this.data.dataMap.formListResult[num].templateValue)
      console.log('申请单')
    }
    this.setData({
      openPageBox: thenS_.openPageBox,
      openPageBox_up: thenS_.openPageBox_up
    })
    this.getpageScrollTo()
  },
  // 查看详情 图片
  getEstablishPdf(id, type, value) { // 1=生成住院建议书 2=生成健康指导 3=生成检验检查单 4=生成处方单
    let params = {
      "id": id,
      "resourceType": type,
      "type": 2,
      "template": value
    }
    app.http.getEstablishPdf(params, true).then(res => {
      let imgUrl = res.data.url;
      switch (type) {
        case 1:
          thenS_.hospitalization_imgurl = imgUrl
          break;
        case 2:
          thenS_.guidance_imgurl = imgUrl
          break;
        case 3:
          thenS_.checklist_imgurl = imgUrl
          break;
        case 4:
          thenS_.prescription_imgurl = imgUrl
          break;
        case 5:
          thenS_.application_imgurl = imgUrl
          break;
      }
      this.setData({
        prescription_imgurl: thenS_.prescription_imgurl,
        guidance_imgurl: thenS_.guidance_imgurl,
        hospitalization_imgurl: thenS_.hospitalization_imgurl,
        checklist_imgurl: thenS_.checklist_imgurl,
        application_imgurl: thenS_.application_imgurl
      })
    }).catch(err => {
      $service.showToast(err.msg)
    })
  },
  // 监听网络变化
  watchNetWork() {
    wx.onNetworkStatusChange((res) => {
      if (res.isConnected) {
        this.initWebSocket();
        if (this.data.log_type == 1 && !this.data.doctorEnd) {
          this.startRTC();
        }
      } else {
        $service.showToast('网络连接异常')
      }
    })
  },

  // 医生离线后弹窗操作
  modalOver() { //结束问诊
    this.setData({
      refundDialogShow: true
    })
  },
  modalBlack() { //返回首页
    app.webSocket.sendWebSocketMsg({
      data: {
        "logId": logId,
        "packageType": 13
      },
      success: () => {
        wx.reLaunch({
          url: '/pages/user_index/user_index'
        })
      }
    })
  },
  modalWait() { // 继续等待
    app.webSocket.sendWebSocketMsg({
      data: {
        "doctorId": doctorId, //医生id
        "patientIM": this.data.myIM,
        "packageMsg": "",
        "packageType": 24,
      },
      success: () => {
        this.setData({
          showModal: false
        })
      },
      fail: () => {
        $service.showToast('操作失败')
      }
    })
  },
  // --------

  getMessageheight() { //获取底部操作栏高度
    let query = wx.createSelectorQuery();
    query.select('.message').boundingClientRect(rect => {
      if (rect) {
        let clientHeight = rect.height;
        let clientWidth = rect.width;
        let ratio = 750 / clientWidth;
        let messageHeight = clientHeight * ratio;
        this.setData({
          messageHeight
        })
      }
    }).exec();
  },
})
